﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using AMM.Business;
using AMM.Business.Project;
using AMM.CustomWinControls;
using AMM.Model;
using AMM.Model.Project;
using AMM.UserControls;
using Microsoft.Reporting.WinForms;

namespace AMM.Forms.Project {
    public partial class FrmBOM : FrmBOMBase {

        private int _pageIndex;
        private BOMSearchModel _searchModel;
        private BOMProcessor _bomOrderProcessor;
        private List<BOMViewModel> _bomOrderList;

        #region Override

        protected override string FunctionCode {
            get { return "AMM1303"; }
        }

        protected override BaseSearchControl SearchControl {
            get { return new BOMSearchControl(); }
        }

        protected override void Add() {
            this.ResetForms();
            this.ShowEditForm("新增", new BOM() { IsEnabled = true, ClassStatus = ClassStatus.Added });
            base.Add();
        }

        protected override void Copy() {
            this.ResetForms();
            BOM bom = new BOM();
            List<BOMViewModel> selectedList = this.dgvBOMList.GetSelectedRows<BOMViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            if (selectedList.Count > 0) {
                bom = this._bomOrderProcessor.FetchBOMById(selectedList[0].Key);
                bom.ModifiedBy = null;
                bom.ModifiedDatetime = null;
                bom.AuditedBy = null;
                bom.AuditedDatetime = null;
            }
            bom.IsEnabled = true;
            bom.ClassStatus = ClassStatus.Added;
            this.ShowEditForm("复制", bom);
            base.Copy();
        }

        protected override void Amend() {
            List<BOMViewModel> selectedList = this.dgvBOMList.GetSelectedRows<BOMViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            BOM bomOrder = this._bomOrderProcessor.FetchBOMById(selectedList[0].Key);
            if ((AuditStatus)bomOrder.BOMStatus == AuditStatus.Audited) {
                this.ShowInfo("审核的 BOM 单不能被修改！");
                return;
            }
            bomOrder.ClassStatus = ClassStatus.Updated;
            this.ShowEditForm("修改", bomOrder);
            base.Amend();
        }

        protected override void Save() {
            base.Save();
        }

        protected override void Delete() {
            List<BOMViewModel> selectedList = this.dgvBOMList.GetSelectedRows<BOMViewModel>();
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                this._bomOrderProcessor.Delete(selectedList.Select(x => x.Key).ToArray());
                this.MDIParent.SetStatusInformation("删除成功");
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                base.Delete();
            });
        }

        protected override void Audit() {
            List<BOMViewModel> selectedList = this.dgvBOMList.GetSelectedRows<BOMViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                string resultMsg = string.Empty;
                BOM bomOrder = this._bomOrderProcessor.FetchBOMById(selectedList[0].Key);
                if (bomOrder.BOMStatus == (int)AuditStatus.Audited) {
                    if (this.ShowQuestion("BOM 单已经通过审核，确定将取消审核状态！") == DialogResult.No) { return; }
                    bomOrder.BOMStatus = (int)AuditStatus.Waiting;
                    resultMsg = "取消审核成功";
                }
                else {
                    bomOrder.BOMStatus = (int)AuditStatus.Audited;
                    resultMsg = "审核成功";
                }
                bomOrder.AuditedBy = LoginUserName;
                this._bomOrderProcessor.Audit(bomOrder);
                this.MDIParent.SetStatusInformation(resultMsg);
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                base.Audit();
            });
        }

        protected override void Print() {
            List<BOMViewModel> selectedList = this.dgvBOMList.GetSelectedRows<BOMViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                this.PrintHelperIns = new PrintHelper("BOMPrint.rdlc", this.Text);
                this.PrintHelperIns.ReportDataSources.Add(new ReportDataSource("ds", selectedList));
                base.Print();
            }, () => {
                // for hiding
                this.PrintHelperIns.Dispose();
            });
        }

        protected override void Search(object sender, FrmSearch.SearchArgs e) {
            this.CreateNewThread(() => {
                if (e.IsRevert) {
                    this._searchModel = new BOMSearchModel();
                }
                else {
                    this._searchModel = (BOMSearchModel)e.SearchModel;
                }
            }, () => {
                this.BindBOMList();
            });
        }

        #endregion

        public FrmBOM() {
            InitializeComponent();

            this.dgvBOMList.DataGridViewModelType = typeof(BOMViewModel);
            this.dgvBOMDetailList.DataGridViewModelType = typeof(BOMDetailsViewModel);
        }

        #region Private methods

        private bool frmEdit_Edit(object sender, FrmEdit.EditArgs e) {
            bool resultFlag = false;
            BOM bomOrder = (BOM)e.EditModel;
            if (bomOrder.BOMDetails.Count == 0) {
                this.ShowError("请添加 BOM 明细记录！");
                return false;
            }
            this.PreventCancel = true;
            this.CreateNewThread(() => {
                if (bomOrder.ClassStatus == ClassStatus.Added) {
                    bomOrder.CreatedBy = LoginUserName;
                    this._bomOrderProcessor.Insert(bomOrder);
                }
                else {
                    bomOrder.ModifiedBy = LoginUserName;
                    this._bomOrderProcessor.Update(bomOrder);
                }
                resultFlag = true;
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                if (resultFlag) {
                    this.MDIParent.SetStatusInformation("保存成功");
                    this.FormEdit.Close();
                }
            });
            this.Save();
            return true;
        }

        private void ResetForms() {
            this.BindBOMList();
            this.BindBOMDetailsList(0);
        }

        private void BindBOMList() {
            this.CreateNewThread(() => {
                this._bomOrderList = this._bomOrderProcessor.FetchBOMViewModelList(this._searchModel, this._pageIndex);
            }, () => {
                this.dgvBOMList.DataSource = new SortableBindingList<BOMViewModel>(this._bomOrderList);
                this.pceList.Records = this._searchModel.Records;
                this.pceList.DataBind();
            });
        }

        private void BindBOMDetailsList(int bomId) {
            List<BOMDetailsViewModel> detailsList = new List<BOMDetailsViewModel>();
            this.CreateNewThread(() => {
                if (bomId != 0) {
                    detailsList = this._bomOrderProcessor.FetchBOMDetailsViewModelList(bomId);
                }
            }, () => {
                this.dgvBOMDetailList.DataSource = new SortableBindingList<BOMDetailsViewModel>(detailsList);
            });
        }

        private void ShowEditForm(string title, BOM bomOrder) {
            this.CreateNewThread(() => {
                Thread.Sleep(100);
            }, () => {
                BOMEditControl editControl = new BOMEditControl();
                this.FormEdit = new FrmEdit();
                editControl.BaseEditModel = bomOrder;
                editControl.ValidatorForEdit = this.FormEdit.validatorForEdit;
                this.FormEdit.Controls.Add(editControl);
                this.FormEdit.Edit += new FrmEdit.EditEventHandler(frmEdit_Edit);
                this.FormEdit.Text = string.Format("{0}{1}", title, this.Text);
                FrmEntry.LoadAndRunDialog(this.FormEdit);
            });
        }

        #endregion

        private void FrmBOM_Load(object sender, EventArgs e) {
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                this._bomOrderProcessor = new BOMProcessor(this.pceList.PageSize);
                this._searchModel = new BOMSearchModel();
                this._pageIndex = 1;
            }, () => {
                this.WindowState = FormWindowState.Maximized;
                this.ResetForms();
                this.PreventCancel = false;
            });
        }

        private void pceList_Paging(object sender, PaginationArgs e) {
            this._pageIndex = e.PageIndex;
            this.BindBOMList();
        }

        private void dgvBOMList_DoubleClick(object sender, EventArgs e) {
            if (this.dgvBOMList.CurrentRow != null) {
                int bomId = (int)this.dgvBOMList.CurrentRow.Cells["Key"].Value;
                this.BindBOMDetailsList(bomId);
            }
        }

    }
}
